package com.voice.core.connection.entity;

import com.voice.core.entity.HttpHeader;
import com.voice.core.ResponseCodeEnum;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class StreamData {

    private HttpHeader headers = new HttpHeader();
    List<byte[]> data = new ArrayList();
    private int dataSize;

    public void addHeaders(HttpHeader header) {
        this.headers.putAll(header);
    }

    public void addData(byte[] bytes) {
        this.data.add(bytes);
        this.dataSize += bytes.length;
    }

    public byte[] readAllData() {
        if (data == null || data.size() == 0) {
            return new byte[0];
        } else {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(dataSize);
            Iterator iterator = data.iterator();
            while (iterator.hasNext()) {
                byte[] bytes = (byte[]) iterator.next();
                outputStream.write(bytes, 0, bytes.length);
            }
            return outputStream.toByteArray();
        }
    }

    public HttpHeader readHeader() {
        return headers;
    }

    public void clearData() {
        this.data.clear();
    }

    public String toString() {
        return "headers: " + this.headers + ", content: " + new String(this.readAllData());
    }

    public HttpHeader getHeaders() {
        return this.headers;
    }

    public List<byte[]> getData() {
        return this.data;
    }

    public int getDataSize() {
        return this.dataSize;
    }

    public boolean isOk(){
        return this.getHeaders().code()== ResponseCodeEnum.Success.getCode();
    }

}
